package com.xky.ui.module.productManagement.update;

import com.xky.pojo.Products;
import com.xky.utils.DBUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class UpdateProduct extends JFrame {
    private JPanel mainPanel, headerPanel, formPanel, buttonPanel;
    private JTextField[] textFields;
    private JComboBox<String> unitComboBox;
    private JComboBox<String> isActiveComboBox;
    private JButton updateButton, queryButton;
    
    // 预定义的有效计量单位列表
    private static final Set<String> VALID_UNITS = new HashSet<>(Arrays.asList(
            "个", "箱", "袋", "瓶", "千克", "克", "吨", "升", "毫升", "米", "厘米", "套",
            "件", "双", "台", "包", "盒", "桶", "卷", "张", "只", "块", "片", "支"
    ));
    
    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);
    private static final Color QUERY_BUTTON_COLOR = new Color(46, 204, 113);

    public UpdateProduct() {
        initializeFrame();
        initComponents();
        setVisible(true);
    }

    private void initializeFrame() {
        setTitle("商品信息修改");
        setSize(550, 700);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initComponents() {
        // 创建主面板并设置背景渐变
        mainPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                int w = getWidth();
                int h = getHeight();
                GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
                g2d.setPaint(gp);
                g2d.fillRect(0, 0, w, h);
            }
        };
        mainPanel.setLayout(new BorderLayout(10, 10));
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));

        // 1. 头部面板
        createHeaderPanel();

        // 2. 表单面板
        createFormPanel();

        // 3. 按钮面板
        createButtonPanel();

        // 添加事件监听
        setupEventListeners();

        add(mainPanel);
    }

    private void createHeaderPanel() {
        headerPanel = new JPanel(new BorderLayout());
        headerPanel.setOpaque(false);
        
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        titlePanel.setOpaque(false);
        
        JLabel titleLabel = new JLabel("商品信息修改");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        titleLabel.setForeground(PRIMARY_COLOR);
        titlePanel.add(titleLabel);
        
        JPanel hintPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        hintPanel.setOpaque(false);
        
        JLabel hintLabel = new JLabel("请输入商品ID查询后再修改");
        hintLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
        hintLabel.setForeground(Color.GRAY);
        hintPanel.add(hintLabel);
        
        // 添加分隔线
        JSeparator separator = new JSeparator();
        separator.setForeground(PRIMARY_COLOR);
        separator.setPreferredSize(new Dimension(450, 2));
        
        headerPanel.add(titlePanel, BorderLayout.NORTH);
        headerPanel.add(hintPanel, BorderLayout.CENTER);
        headerPanel.add(separator, BorderLayout.SOUTH);
        headerPanel.setBorder(new EmptyBorder(0, 0, 20, 0));
        
        mainPanel.add(headerPanel, BorderLayout.NORTH);
    }

    private void createFormPanel() {
        // 创建带圆角和阴影的面板
        JPanel formCard = createRoundedPanel();
        formCard.setLayout(new BorderLayout());
        
        formPanel = new JPanel(new GridBagLayout());
        formPanel.setOpaque(false);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        String[] labels = {"商品ID *", "商品编码 *", "商品名称 *", "分类ID *", "计量单位 *", "最低库存 *", "是否上架 *"};
        textFields = new JTextField[6];

        Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 16);

        for (int i = 0; i < labels.length; i++) {
            // 添加标签
            gbc.gridx = 0;
            gbc.gridy = i;
            gbc.weightx = 0.3;
            JLabel label = new JLabel(labels[i]);
            label.setFont(labelFont);
            label.setForeground(PRIMARY_COLOR);
            formPanel.add(label, gbc);

            // 添加输入控件
            gbc.gridx = 1;
            gbc.weightx = 0.7;
            
            if (i != 4 && i != 6) { // 不是计量单位和是否上架
                textFields[i > 4 ? i - 1 : i] = new JTextField(20);
                textFields[i > 4 ? i - 1 : i].setFont(fieldFont);
                textFields[i > 4 ? i - 1 : i].setPreferredSize(new Dimension(250, 35));
                formPanel.add(textFields[i > 4 ? i - 1 : i], gbc);
            } else if (i == 4) { // 计量单位使用下拉框
                unitComboBox = new JComboBox<>(VALID_UNITS.toArray(new String[0]));
                unitComboBox.setFont(fieldFont);
                unitComboBox.setPreferredSize(new Dimension(250, 35));
                unitComboBox.setBackground(Color.WHITE);
                formPanel.add(unitComboBox, gbc);
            } else {
                isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
                isActiveComboBox.setFont(fieldFont);
                isActiveComboBox.setPreferredSize(new Dimension(250, 35));
                isActiveComboBox.setBackground(Color.WHITE);
                formPanel.add(isActiveComboBox, gbc);
            }
        }

        formCard.add(formPanel, BorderLayout.CENTER);
        formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        mainPanel.add(formCard, BorderLayout.CENTER);
    }

    private void createButtonPanel() {
        buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setOpaque(false);

        queryButton = new JButton("查询");
        styleButton(queryButton, QUERY_BUTTON_COLOR);
        
        updateButton = new JButton("修改");
        styleButton(updateButton, BUTTON_COLOR);

        // 初始状态下修改按钮不可用
        updateButton.setEnabled(false);

        buttonPanel.add(queryButton);
        buttonPanel.add(updateButton);

        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
    }

    private void styleButton(JButton button, Color bgColor) {
        button.setFont(new Font("微软雅黑", Font.BOLD, 16));
        button.setPreferredSize(new Dimension(120, 40));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
    }
    
    /**
     * 创建带圆角和阴影的面板
     */
    private JPanel createRoundedPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setColor(Color.WHITE);
                g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
            }
        };
        panel.setOpaque(false);
        
        // 添加阴影边框
        panel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5),
            BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)
            )
        ));
        
        return panel;
    }

    private void setupEventListeners() {
        // 查询按钮事件
        queryButton.addActionListener(e -> {
            String productIdStr = textFields[0].getText().trim();
            if (productIdStr.isEmpty()) {
                JOptionPane.showMessageDialog(this, "请输入商品ID", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            try {
                int productId = Integer.parseInt(productIdStr);
                Products product = findProductById(productId);
                if (product != null) {
                    // 填充表单数据
                    textFields[0].setText(String.valueOf(product.getProductId()));
                    textFields[1].setText(product.getProductCode());
                    textFields[2].setText(product.getProductName());
                    textFields[3].setText(String.valueOf(product.getCategoryId()));
                    
                    // 设置计量单位下拉框
                    for (int i = 0; i < unitComboBox.getItemCount(); i++) {
                        if (unitComboBox.getItemAt(i).equals(product.getUnitOfMeasure())) {
                            unitComboBox.setSelectedIndex(i);
                            break;
                        }
                    }
                    
                    textFields[4].setText(String.valueOf(product.getMinStockLevel()));
                    
                    // 设置是否上架下拉框
                    isActiveComboBox.setSelectedIndex("1".equals(product.getIsActive()) ? 0 : 1);

                    // 启用修改按钮
                    updateButton.setEnabled(true);
                } else {
                    JOptionPane.showMessageDialog(this, "未找到该商品", "提示", JOptionPane.WARNING_MESSAGE);
                    updateButton.setEnabled(false);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的数字ID", "输入错误", JOptionPane.WARNING_MESSAGE);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "查询失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        // 修改按钮事件
        updateButton.addActionListener(e -> {
            try {
                // 首先进行输入校验
                if (!validateInputs()) {
                    return; // 如果校验不通过，直接返回
                }
                
                Integer productId = Integer.valueOf(textFields[0].getText().trim());
                String productCode = textFields[1].getText().trim();
                String productName = textFields[2].getText().trim();
                int categoryId = Integer.parseInt(textFields[3].getText().trim());
                String unitOfMeasure = (String) unitComboBox.getSelectedItem();
                int minStockLevel = Integer.parseInt(textFields[4].getText().trim());
                String isActive = isActiveComboBox.getSelectedIndex() == 0 ? "1" : "0"; // "是"对应1，"否"对应0

                if (updateProduct(productId, productCode, productName, categoryId, unitOfMeasure, minStockLevel, isActive)) {
                    JOptionPane.showMessageDialog(this, "商品信息更新成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                   dispose();
                } else {
                    JOptionPane.showMessageDialog(this, "商品信息更新失败", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "数据库错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
    }
    
    /**
     * 校验用户输入的数据
     * @return 如果所有输入都有效返回true，否则返回false
     */
    private boolean validateInputs() {
        // 1. 校验商品ID
        if (textFields[0].getText().trim().isEmpty()) {
            showValidationError("商品ID不能为空");
            return false;
        }
        
        try {
            Integer.parseInt(textFields[0].getText().trim());
        } catch (NumberFormatException e) {
            showValidationError("商品ID必须是数字");
            return false;
        }
        
        // 2. 校验商品编码
        if (textFields[1].getText().trim().isEmpty()) {
            showValidationError("商品编码不能为空");
            return false;
        }
        
        // 3. 校验商品名称
        if (textFields[2].getText().trim().isEmpty()) {
            showValidationError("商品名称不能为空");
            return false;
        }
        
        // 4. 校验分类ID
        if (textFields[3].getText().trim().isEmpty()) {
            showValidationError("分类ID不能为空");
            return false;
        }
        
        try {
            Integer.parseInt(textFields[3].getText().trim());
        } catch (NumberFormatException e) {
            showValidationError("分类ID必须是数字");
            return false;
        }
        
        // 5. 校验最低库存
        if (textFields[4].getText().trim().isEmpty()) {
            showValidationError("最低库存不能为空");
            return false;
        }
        
        try {
            int minStock = Integer.parseInt(textFields[4].getText().trim());
            if (minStock < 0) {
                showValidationError("最低库存不能小于0");
                return false;
            }
        } catch (NumberFormatException e) {
            showValidationError("最低库存必须是数字");
            return false;
        }
        
        // 所有校验通过
        return true;
    }
    
    private void showValidationError(String message) {
        JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
    }

    private Products findProductById(int productId) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement("SELECT * FROM products WHERE product_id = ?");
            preparedStatement.setInt(1, productId);
            resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                Products product = new Products();
                product.setProductId(resultSet.getInt("product_id"));
                product.setProductCode(resultSet.getString("product_code"));
                product.setProductName(resultSet.getString("product_name"));
                product.setCategoryId(resultSet.getInt("category_id"));
                product.setUnitOfMeasure(resultSet.getString("unit_of_measure"));
                product.setMinStockLevel(resultSet.getInt("min_stock_level"));
                product.setIsActive(resultSet.getString("is_active"));
                return product;
            }
            return null;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, resultSet);
        }
    }

    /**
     * 修改商品信息的方法
     * @param productId
     * @param productCode
     * @param productName
     * @param categoryId
     * @param unitOfMeasure
     * @param minStockLevel
     * @param isActive
     * @return
     * @throws SQLException
     */
    private boolean updateProduct(Integer productId, String productCode, String productName, int categoryId,
                                  String unitOfMeasure, int minStockLevel, String isActive) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement(
                    "UPDATE products SET product_code = ?, product_name = ?, category_id = ?, " +
                            "unit_of_measure = ?, min_stock_level = ?, is_active = ?, updated_time = NOW() " +
                            "WHERE product_id = ?");
            preparedStatement.setString(1, productCode);
            preparedStatement.setString(2, productName);
            preparedStatement.setInt(3, categoryId);
            preparedStatement.setString(4, unitOfMeasure);
            preparedStatement.setInt(5, minStockLevel);
            preparedStatement.setString(6, isActive);
            preparedStatement.setInt(7, productId);

            return preparedStatement.executeUpdate() > 0;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }

    private void clearForm() {
        for (JTextField field : textFields) {
            field.setText("");
        }
        unitComboBox.setSelectedIndex(0);
        isActiveComboBox.setSelectedIndex(0);
        updateButton.setEnabled(false);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(UpdateProduct::new);
    }
}